// 基本信息
import DialogBox from "@/components/DialogBox";
import SelectDeviceListAll from "@/components/Sansan/SelectDeviceListAll";
import SelectProductList from "@/components/Sansan/SelectProductList";
import { ElForm } from "element-plus";
import { defineComponent, PropType } from "vue";
interface DeviceForm {
	[key: string]: any;
}
export default defineComponent({
	props: {
		detail: {
			type: Object as PropType<DeviceForm>,
			default() {
				return {};
			}
		}
	},
	emits: ["submit"],
	setup(props, { attrs, emit }) {
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const formRule = reactive({
			name: [{ required: true, message: "请输入规则名称", trigger: "change" }],
			desc: [{ required: true, message: "请输入规则描述", trigger: "change" }]
		});

		const state = reactive({
			productList: [],
			deviceList: [],
			bindType: "product"
		});
		const validData = () => {
			formRef.value?.validate(valid => {
				if (valid) {
					props.detail.productId = state.productList.join(",");
					props.detail.devSn = state.deviceList.join(",");
					emit("submit");
				}
			});
		};
		watchEffect(() => {
			if (attrs.visible) {
				//默认为软规则
				state.bindType = props.detail.productId ? "product" : "device";
				//多选扩展字段
				state.productList = props.detail.productId?.split(",") || [];
				state.deviceList = props.detail.devSn?.split(",") || [];
			}
		});
		const changeBindType = () => {
			if (state.bindType == "product") {
				state.deviceList = [];
				props.detail.devSn = "";
			} else {
				state.productList = [];
				props.detail.productId = "";
			}
		};
		return () => {
			return (
				<DialogBox {...attrs} onConfirm={() => validData()}>
					<el-form model={props.detail} ref={formRef} rules={formRule} label-width="100px">
						<el-form-item label="规则名称" prop="name">
							<el-input v-model={props.detail.name} placeholder="请输入规则名称" />
						</el-form-item>
						<el-form-item label="数据范围" prop="bindType">
							<el-select v-model={state.bindType} onChange={() => changeBindType()}>
								<el-option label="关联产品" value="product"></el-option>
								<el-option label="关联设备" value="device"></el-option>
							</el-select>
						</el-form-item>
						{state.bindType == "product" ? (
							<el-form-item label="关联产品" prop="productId">
								<SelectProductList multiple v-model={state.productList} />
							</el-form-item>
						) : null}
						{state.bindType == "device" ? (
							<el-form-item label="关联设备" prop="devSn">
								<SelectDeviceListAll multiple v-model={state.deviceList} />
							</el-form-item>
						) : null}
						<el-form-item label="规则描述" prop="desc">
							<el-input v-model={props.detail.desc} placeholder="请输入规则描述" type="textarea" auto-size />
						</el-form-item>
					</el-form>
				</DialogBox>
			);
		};
	}
});
